package com.iflytek.uoamp.notify.wechat.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http工具类
 * @ClassName: HttpUtils
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author Administrator
 * @date 2017-4-6 下午3:30:11
 */
public class HttpUtils {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
	private static final HttpClient httpClient;
	static {
		MultiThreadedHttpConnectionManager connectionManager =
                new MultiThreadedHttpConnectionManager();
		connectionManager.getParams().setConnectionTimeout(10000); // 连接5秒超时
		connectionManager.getParams().setSoTimeout(30000);// 读取30秒超时
		// 构造HttpClient的实例
		httpClient = new HttpClient(connectionManager);
	}
	
	
	/**
     * 执行一个HTTP POST请求，返回请求响应的HTML
     * 
     * @param url
     *            请求的URL地址
     * @param params
     *            请求的查询参数,可以为null
     * @return 返回请求响应的HTML
     */
    @SuppressWarnings("deprecation")
    public static String doPost(String url, String json) {
    	LOGGER.debug("doPost url is {},parajson is {}",new Object[]{url,json});
        String response = null;
        PostMethod method = new PostMethod(url);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        // 设置Http Post数据       
        try {
            method.setRequestBody(json); 
            method.setRequestHeader("Content-type", "application/json");
          
            httpClient.executeMethod(method);
            response = method.getResponseBodyAsString();

        } catch (Exception e) {
            LOGGER.error("doPost url is {},parajson is {},Exception is {}",new Object[]{url,json,e});
        } finally {
            method.releaseConnection();
        }
        LOGGER.debug("doPost url is {},parajsonjson is {},response is {}",new Object[]{url,json,response});
        return response;
    }
}
